package com.zhuiyun.project.security.customizelogin.wx;

import com.zhuiyun.project.api.appuser.entity.User;
import com.zhuiyun.project.api.wxlogin.service.impl.WxLoginServiceImpl;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.security.commonhandler.RequestMethodVerification;
import com.zhuiyun.project.security.commonhandler.SecurityLoginUserVerification;
import com.zhuiyun.project.security.commonhandler.SecurityWxLoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName CustomLoginFilter
 * @Description 微信登录过滤器
 * @Author zcy
 * @Date 2023/4/5 11:34
 **/
public class WechatFilter extends AbstractAuthenticationProcessingFilter  {
    @Autowired
    private WxLoginServiceImpl wxLoginService;
    public WechatFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        // 仅使用POST方法提交
        RequestMethodVerification.postVerification(request);
        // 获取登录信息
        SecurityWxLoginUser user = SecurityLoginUserVerification.getWxLoginUser(request);
        // 获取信息
        String userPhone = user.getUserPhone();
        String openId = user.getOpenId();
        //验证是否为空
        SecurityLoginUserVerification.vitParams(userPhone, EmErrorCode.USERNAME_IS_NULL.getErrMsg());
        //验证是否为空
        SecurityLoginUserVerification.vitParams(openId, EmErrorCode.PASSWORD_IS_NULL.getErrMsg());
        //认证
        WechatAuthenticationToken token = new WechatAuthenticationToken(openId, userPhone);
        //获取 头部信息 让合适的provider 来验证他
        token.setDetails(this.authenticationDetailsSource.buildDetails(request));
        //获取用户信息
        User userByPhone = wxLoginService.getUserByPhone(userPhone);
        //判断是否禁用
        //判断用户是否被禁用
        if(userByPhone!=null&&userByPhone.getProhibition() == 1){
            throw new AuthenticationServiceException("该账号已被禁用");
        }
        //交给 manager 发证
        return this.getAuthenticationManager().authenticate(token);
    }

}
